//路由鉴权，
//鉴权->项目中路由能不能被别的权限的设置（某个路由什么条件下可以访问，什么条件下不可以访问）
import router from '@/router'
import setting from './setting'
import nprogress from 'nprogress'
// 引入仓库中的用户信息
import useUserSrore from './store/modules/user'
import pinia from './store'
let userStore = useUserSrore(pinia)
nprogress.configure({ showSpinner: false })
import 'nprogress/nprogress.css'
//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = setting.title + '-' + to.meta.title
  nprogress.start()
  // 获取用户token，判断是否登录
  let token = userStore.token
  let userName = userStore.userName
  if (token) {
    // 登录成功，不能访问login，指向首页
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (userName) {
        next()
      } else {
        // 没有用户信息，发请求获取用户信息
        try {
          await userStore.userInfo()
          next()
        } catch {
          // token过期，手动修改本地存储token
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    console.log(to)
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
// 全局后置守卫
router.afterEach((to: any, from: any, next: any) => {
  nprogress.done()
})
